<template>
  <a-spin :spinning="loading">
    <a-select v-model:value="tcmType" class="w-20 z-20" @change="onChangeMedicineType">
      <a-select-option value="饮片">饮片</a-select-option>
      <a-select-option value="颗粒">颗粒</a-select-option>
    </a-select>
    <div class="flex flex-wrap min-h-[80px] mt-4">
      <template v-for="medicineItem in dataSource" :key="medicineItem.id">
        <div class="3xl:w-[12.5%] w-[20%] item-style" :class="focusKey === medicineItem.key ? 'active' : ''">
          <BaseButton
            confirm-text="确认删除?"
            type="text"
            danger
            :icon="h(CloseOutlined)"
            shape="circle"
            size="small"
            class="delete-btn"
            @click="onDelete(medicineItem)"
          />
          <div class="flex">
            <SelectTable
              v-model:value="medicineItem.mc"
              type="中药"
              class-name="border-b-style text-base"
              :bordered="false"
              :search-params="{ zylb: tcmType }"
              :auto-focus="focusKey === medicineItem.key + '中药'"
              placeholder="药名"
              @select="onSelectMedicine(medicineItem, $event)"
            />
            <BaseInput
              v-model:value="medicineItem.sl"
              v-input-selection
              :auto-focus="focusKey === medicineItem.key + '用量'"
              :bordered="false"
              class="w-28 input-style"
              placeholder="用量"
              suffix="g"
              @keyup.enter="onKeyEnter(medicineItem)"
            />
          </div>
          <div class="use-btn" :class="medicineItem.jf ? 'show' : ''">
            <SelectTags
              v-model:value="medicineItem.jf"
              bind-parent
              :bordered="false"
              type="煎法"
              class="text-xs cursor-pointer"
              tag-class="w-32"
              placeholder="煎法"
              @select="onSelectUse(medicineItem, $event)"
            />
          </div>
        </div>
      </template>
    </div>
    <div class="text-center mt-4">
      <a-button type="primary" @click="onSave">保存</a-button>
    </div>
  </a-spin>
</template>
<script setup>
import { ref, h, createVNode, watch } from 'vue'
import { computed } from 'vue'
import { CloseOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { post } from '@/utils/request'
import useSuitStore from '../store'

const suitStore = useSuitStore()
const emit = defineEmits(['addItem', 'focusNext', 'deleteItem', 'changeItem'])
const focusKey = ref(null)
const tcmType = ref('饮片')
const onSelectMedicine = (row, selected) => {
  row.mc = selected?.mc
  row.sfxm = selected
  setTimeout(() => {
    focusKey.value = row.key + '用量'
  }, 100)
  onAddItem(row.key)
}
const onSelectUse = (row, selected) => {
  row.yf = selected
  row.jf = selected.mc
  onAddItem(row.key)
}

const onAddItem = (key) => {
  const isLast = dataSource.value.at(-1)?.key === key
  isLast && dataSource.value.push({ key: dataSource.value.length })
}
const onSave = async () => {
  const params = dataSource.value.filter((item) => item.mc)
  const { code, msg } = await post('/outp/template/doAddClinicalOrderPackageItem', {
    tcid: suitStore.currentSuit.tcid,
    children: params,
    cjr: suitStore.currentSuit.cjr
  })
  if (code !== 0) return message.error(msg || '保存失败')
  message.success('保存成功')
  getData()
}
const onDelete = async (row) => {
  if (row.id) {
    const { code, msg } = await post('/outp/template/doDelClinicalOrderPackageItem', {
      bh: row.bh,
      tcid: suitStore.currentSuit.tcid,
      cjr: suitStore.currentSuit.cjr
    })
    if (code !== 0) return message.error(msg || '删除失败')
    message.success('删除成功')
    getData()
  } else {
    dataSource.value = dataSource.value.filter((item) => item.key !== row.key)
  }
}
const onKeyEnter = (row) => {
  const currentFocusKey = row.key
  focusKey.value = row.key + 1 + '中药'
  emit('focusNext', currentFocusKey + 1)
}

const params = computed(() => {
  return {
    tcid: suitStore.currentSuit.tcid
  }
})
const { loading, dataSource, getData } = useFetch({
  url: '/outp/template/getClinicalOrderPackageItemList',
  params,
  formatResult: (data) => {
    const res = data.map((item, index) => ({ ...item, key: index }))
    res.push({ key: data.length })
    return res
  },
  onSuccess: (data) => {
    if (data.length > 0) {
      tcmType.value = data[0].zylb || '饮片'
    }
  }
})
const clearItems = async () => {
  const { code } = await post('/outp/template/doDelClinicalAllOrderPackageItem', { tcid: suitStore.currentSuit.tcid })
  if (code !== 0) return message.error('清空失败')
  await getData()
  focusKey.value = 0 + '中药'
}
const onChangeMedicineType = (type) => {
  Modal.confirm({
    title: '确定切换药品类型吗？',
    icon: createVNode(ExclamationCircleOutlined),
    centered: true,
    maskClosable: true,
    width: 560,
    content: createVNode(
      'div',
      { style: 'margin:24px 0;font-size:15px' },
      type === '饮片' ? '若更换为饮片，将自动清空颗粒药品' : '若更换为颗粒，将自动清空饮片药品'
    ),
    onOk() {
      clearItems()
    },
    onCancel() {
      tcmType.value = tcmType.value === '饮片' ? '颗粒' : '饮片'
    }
  })
}
watch(
  () => suitStore.currentSuit.tcid,
  (val) => {
    if (val) {
      getData()
    } else {
      dataSource.value = []
    }
  }
)
</script>
<style lang="less" scoped>
:deep(.item-style) {
  position: relative;
  display: flex;
  align-items: center;
  height: 80px;
  margin-bottom: -2px;
  margin-left: -2px;
  border-color: var(--border-color);
  border-style: dashed;
  border-width: 2px;

  &:hover,
  &.active {
    background-color: #00000007;
    outline: 1px dashed var(--primary-color);
    .use-btn,
    .delete-btn {
      display: block;
    }
  }
  .use-btn,
  .delete-btn {
    position: absolute;
    display: none;
  }
  .use-btn {
    bottom: 0;
    left: 0;
  }
  .show {
    display: block !important;
  }
  .delete-btn {
    top: 0;
    right: 0;
  }
  .ant-input {
    cursor: pointer;
  }
}
:deep(.border-b-style) {
  border-bottom: 1px solid transparent;
  border-radius: 0;
  cursor: pointer;
  &:hover {
    border-bottom: 1px solid var(--primary-color);
  }
}
.input-style {
  padding: 0 12px;
  :deep(.ant-input) {
    padding-right: 4px;
    text-align: center !important;
    border-bottom: 1px solid var(--border-color) !important;
    cursor: pointer;
    &:hover {
      border-bottom-color: var(--primary-color) !important;
    }
  }
}
</style>
